local tracer_ops = {}

local log_reporter = require('skywalking.reporter.log_reporter')
local sync_http_reporter = require('skywalking.reporter.sync_http_reporter')
local Sampler = require("skywalking.sampler")
local async_http_reporter = require('skywalking.reporter.async_http_reporter')

local ngx = ngx

function tracer_ops:optionInstance(service_instance)
    return function(tracer)
        if not service_instance then
            return
        end
        local metadata_buffer = ngx.shared.tracing_buffer
        tracer.service_instance_name = service_instance
        metadata_buffer:set('serviceInstanceName', service_instance)
    end
end

--- 下面是tracer的可选项,包括日志组件, reporter组件，采样器组件
function tracer_ops:optionLogger(logger)
    return function(tracer)
        tracer.logger = logger
    end
end

-- 日志报告器，通过日志打印，方便debug
function tracer_ops:optionLogReporter()
    return function(tracer)
        tracer.reporter = log_reporter.new(tracer.logger)
    end
end

--- 同步报告的服务器地址
function tracer_ops:optionSyncHttpReporter(backend_http_uri)
    return function(tracer)
        tracer.reporter = sync_http_reporter.new(tracer.logger, backend_http_uri)
        -- 启动
        tracer.reporter:boot()
    end
end

--- @param backend_http_uri 异步报告的服务器地址
--- @param filter_url_list url过滤名单, 过滤/user/cs/reg_activate/xxxxxxxxxxxxx --> /user/cs/reg_activate
function tracer_ops:optionAsyncHttpReporter(backend_http_uri, filter_url_list)
    return function(tracer)
        tracer.reporter = async_http_reporter.new(tracer.logger, backend_http_uri, filter_url_list)
        tracer.reporter:boot()
    end
end

--- 随机+URL过滤采样器
--- @param sample_ratio 采样比例:0 ~ 10000
--- @param white_url_map url白名单
--- @param black_url_map url黑名单
function tracer_ops:optionRandomUrlFilterSampler(sample_ratio, white_url_map, black_url_map)
    return function(tracer)
        tracer.sampler = Sampler.randomUrlFilterSampler(sample_ratio, white_url_map, black_url_map)
    end
end

--- 随机+URL过滤采样器
--- @param host_sample_ratio_config 采样比例-host配置
--- @param white_url_map url白名单
--- @param black_url_map url黑名单
--- @param default_sample_ratio 默认采样率
function tracer_ops:optionRandomHostSampler(host_sample_ratio_config, white_url_map, black_url_map, default_sample_ratio)
    return function(tracer)
        tracer.sampler = Sampler.randomRandomHostSampler(host_sample_ratio_config, white_url_map, black_url_map, default_sample_ratio)
    end
end

-- 通过随机数算法采样，sample_ratio取值0~10000
function tracer_ops:optionRandomSampler(sample_ratio)
    return function(tracer)
        tracer.sampler = Sampler.randomSampler(sample_ratio)
    end
end

-- 通过指定bool采样，bool false时表示不采样
function tracer_ops:optionConstSampler(bool)
    return function(tracer)
        tracer.sampler = Sampler.constSampler(bool)
    end
end

-- 通过设置url白名单控制采样，在白名单内可以被采
function tracer_ops:optionURLFilterSampler(white_map)
    return function(tracer)
        tracer.sampler = Sampler.urlFilterSampler(white_map)
    end
end

return tracer_ops
